package com.okRPC.client.transport;

import java.util.concurrent.*;

/**
 * Description: This is a sample class.
 * Author: Simon
 */
public class RpcFuture<T> implements Future<T> {

    private T response;

    /**
     * 因为请求和响应是一一对应的，所以这里是1
     * 使用 CountDownLatch 等待线程
     */
    private CountDownLatch countDownLatch = new CountDownLatch(1);

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return this.response!=null;
    }

    @Override
    public T get() throws InterruptedException, ExecutionException {
        countDownLatch.await();
        return this.response;
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        countDownLatch.await(timeout,unit);
        return this.response;
    }

    public void setResponse(T response){
        this.response=response;
        countDownLatch.countDown();
    }
}
